Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
Problem of using element.addEventListen("keydown", function) over document.addEventListener("keydown", function)

I have a NodeList of button elements numbers. I want each of the elements listen to keydown event in respective to their own textContent.

When I use document.addEventHandlers("keydown", function), it works fine.

Method 1:

document.addEventListener("keydown", (e)=>{
numbers.forEach(number=>{
    if (number.textContent === e.key){
        addNumber(number)
    }})})

However, it stops working when I use this instead:

Method 2:

numbers.forEach(number=>number.addEventListener("keydown", (e)=>{
    if (number.textContent === e.key){
        addNumber(number);
    }}))

The first method seems not efficient to me since it has to make comparison to every items in numbers everytime "keydown" is fired. Can anyone tell me why the method 2 don't work as method 1?

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

If the problem is the performance, you can map your numbers in a map/dictionary with their textContent as a key and the number object as a value. Then:

document.addEventListener("keydown", (e) => {
    var number = numbersByKey[e.Key];
    if (number)
        addNumber(number);
})
about 4 years ago · Santiago Gelvez Relatório

0

    document.addEventListener("keydown", (e)=>{
    numbers.forEach(number=>{
        if (number.textContent === e.key){
             addNumber(number)
        }})})

In the above code, you are adding a keydown listener for the document itself, so whenever you press a key on the keyboard, this event is fired.

     numbers.forEach(number=>number.addEventListener("keydown", (e)=>{
         if (number.textContent === e.key){
             addNumber(number);
         }}))

In this code, you are adding a keydown listener to the individual element, so only if the element is focused the keydown event will be fired for that element

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda